package com.example.oa;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class AuthFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String uri = httpServletRequest.getRequestURI();
//        System.out.println(uri);
        String user = (String) httpServletRequest.getSession().getAttribute("name");


        if (uri.contains("admin")) {
            // 访问admin文件的路径
            int role = -1;
            // 先设置初值 未登录
            if (httpServletRequest.getSession().getAttribute("role") != null) {
                //登陆了 （1. 普通用户 role=0;  2.管理员 role=1; 3.未登录)
                role = (int) httpServletRequest.getSession().getAttribute("role");
            }
            if (role != 1) {
                //1.普通用户 role=0;  2.未登录
                httpServletRequest.setAttribute("error", "没有权限");
                // 访问到根目录下的index.jsp
                httpServletRequest.getRequestDispatcher("/index.jsp").forward(request, response);

            }
        }
        // 如果 都不含有 直接放行
        chain.doFilter(request, response);
    }
}
/*
1(admin)
123
/index.jsp
        http://localhost:8080/
        /
        /employee
        http://localhost:8080/employee
        /employee
        /admin/admin.jsp
        http://localhost:8080/admin/admin.jsp
        /admin/admin.jsp
*/
